<?php
require_once PATH_SITE.'cn/royan/php/utils/Crypt.class.php';
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
require_once PATH_SITE.'org/puremvc/php/patterns/proxy/Proxy.php';
/**
 * Description of DispatchDataProxy
 *
 * @author yanr
 */
class DispatchDataProxy extends Proxy
{
    const NAME = "DispatchDataProxy";
    
    protected $crypt;

    //put your code here
    public function __construct() {
        parent::__construct( DispatchDataProxy::NAME );
        
        $this->crypt = Crypt::getInstance();
    }
    
    public function dispatch( $data )
    {
        IF( is_array( $data["client"] ) )
        {
            $this->sendMultipleMessageHandler($data["message"], $data["client"], $data["cryptable"]);
        }
        ELSE
        {
            $this->sendSingleMessageHandler($data["message"], $data["client"], $data["cryptable"]);
        }
    }
    
    private function sendSingleMessageHandler( $message, $client, $cryptable = TRUE )
    {
        if( $cryptable ){
            $length = strlen( $message );
            $offset = "";
            for( $i = 0; $i < 6 - strlen( $length ); $i++ ){
                $offset .= "0";
            }
            $message = $offset.$length.$message;
            $message = $this->crypt->encrypt( $message );
            $offset = "";
            for( $i = 0; $i < 6 - strlen( $length ); $i++ ){
                $offset .= "0";
            }
            $length = strlen( $message );
            $message = $offset.$length.$message;
        }
        IF( @socket_write( $client, $message.chr( 0 ) ) < 0 )
        {
            Logger::trace( "socket_write() failed: reason: " . socket_strerror( $client ) );
            RETURN FALSE;
        }
        ELSE
        {
            Logger::trace( "send message:\r\n".$message."\r\nto ".$client." send success!" );
            RETURN TRUE;
        }
    }

    private function sendMultipleMessageHandler( $message, $list, $cryptable = TRUE )
    {
        if( $cryptable ){
            $message = $this->crypt->encrypt( $message );
        }
        $errorShow = TRUE;
        FOREACH( $list AS $client )
        {
            IF ( !$this->sendSingleMessageHandler( $message, $client, $cryptable ) )
            {
                $errorShow = FALSE;
            }
        }
        IF ( $errorShow )
        {
            Logger::trace( "send message:\r\n".$message."\r\nsend success!" );
        }
    }
}

?>
